package com.bank.lenovoz5;

import android.graphics.Point;
import android.os.RemoteException;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.text.TextUtils;
import android.util.Log;

import com.entity.BankOrder;
import com.entity.SMSCode;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.LogToFile;

import java.text.DecimalFormat;

import static android.content.ContentValues.TAG;
import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.PAUSE;
import static com.utils.ChatClient.RUNING;
import static com.utils.ChatClient.S_paused_C;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.requestSMSCode;
import static com.utils.ChatClient.setDevicesLog;
import static com.utils.ChatClient.user;

/**
 * 项目名称：yzf_android
 * 类描述：中国银行自动脚本
 * 创建人：Administrator
 * 创建时间：2019/7/15 11:06
 * 修改人：Administrator
 * 修改时间：2019/7/15 11:06
 * 修改备注：键盘截图未处理，待开发
 */
public class Z5BOCBbank {
    private static String BANK_NAME = "中国银行";
    private static String BANK_FLAG = "BOC";

    // 2016分辨率 卡号键盘 顺序0123456789
    private int[][] xy_bank_no_2016 = new int[][]{
            {555, 1960},
            {310, 1440}, {555, 1440}, {800, 1440},
            {310, 1610}, {555, 1610}, {800, 1610},
            {310, 1780}, {555, 1780}, {800, 1780}
    };

    // 2016分辨率 卡号键盘 顺序0123456789
    private int[][] xy_sms_2016 = new int[][]{
            {555, 2015},
            {190, 1530}, {555, 1530}, {800, 1530},
            {190, 1690}, {555, 1690}, {800, 1690},
            {190, 1855}, {555, 1855}, {800, 1855}
    };

    // 2016分辨率 金额键盘顺序为123456789.0
    private static int[][] xy_123_2016 = new int[][]{
            {190, 1410}, {555, 1410}, {910, 1410},
            {190, 1610}, {555, 1610}, {910, 1610},
            {190, 1800}, {555, 1800}, {910, 1800},
            {190, 1990}, {555, 1990}
    };

    // 2016分辨率 手势密码坐标顺序为：123456789
    private static int[][] xy_gesture_2016 = new int[][]{
            {230, 935}, {540, 935}, {850, 935},
            {230, 1245}, {540, 1245}, {850, 1245},
            {230, 1560}, {540, 1560}, {850, 1560}
    };
    private UiDevice mDevice;
    private String orderBankName;
    private String balance;
    private int smsFlag = 1;

    public Z5BOCBbank(UiDevice mDevice) throws UiObjectNotFoundException {
        this.mDevice = mDevice;
        homeTransfer();
    }

    private void gesturesOfLanding(String password) throws RemoteException {
        sleep(ChatClient.overtime_3);
        showMsg("点击汇款金额");
        char[] pwd = password.toCharArray();//char数组
        Point[] pp = new Point[pwd.length];
        for (int i = 0; i < pwd.length; i++) {
            Point point = new Point();
            int p = Integer.valueOf(pwd[i] + "") - 1;
            point.set(xy_gesture_2016[p][0], xy_gesture_2016[p][1]);
            pp[i] = point;
        }
        // 唤醒屏幕
        mDevice.wakeUp();
        mDevice.swipe(pp, 10);
    }

    /**
     * 主页开始逻辑----点击转账
     */
    private void homeTransfer() throws UiObjectNotFoundException {
        Constants.tryingToReadAccountInformation(mDevice, BANK_NAME);
        sleep(ChatClient.overtime_5);
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime) {
                ChatClient.timer(LogToFile.getMethodName(), "获取登录信息超时");
                return;
            }
            UiObject nextAD4 = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_updata"));
            if (nextAD4.exists()) {
                showMsg("暂不更新");
                nextAD4.click();
            }
            UiObject mTV_myAccount = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_item").text("转账"));
            if (mTV_myAccount.exists()) {
                showMsg("点击---转账");
                mTV_myAccount.click();
                break;
            }
        }
        // 获取账户信息
        Constants.getAccountInformation(Constants.getMethod(0));
        try {
            if (TextUtils.isEmpty(user.getPwd())) {
                showMsg("user.getPwd()==null");
                return;
            }
            gesturesOfLanding(user.getPwd());
            login();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户账号密码登录
     */
    private void login() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_10);
        showMsg("进入---登录页面");
        // 判断是否有广告有广告关闭
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_8) {
                showMsg("没有广告");
                break;
            }
            UiObject nextAD = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_action")
                    .text("下一条"));
            if (nextAD.exists()) {
                showMsg("有广告");
                nextAD.click();
            }
            UiObject nextAD1 = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_action"));
            if (nextAD1.exists()) {
                showMsg("广告---关闭");
                nextAD1.click();
                break;
            }
            UiObject nextAD3 = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/nextBtn")
                    .text("下一条"));
            if (nextAD3.exists()) {
                showMsg("有广告");
                nextAD3.click();
            }
            UiObject nextAD2 = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/confirmBtn")
                    .text("我知道了"));
            if (nextAD2.exists()) {
                showMsg("广告---我知道了");
                nextAD2.click();
                break;
            }
        }
        while (true) {
            UiObject mTV = mDevice.findObject(new UiSelector().text("账号转账").className("android.widget.TextView"));
            showMsg("检测账号转账");
            if (mTV.exists()) {
                showMsg("登陆成功进入转账页面");
                ChatClient.loginS();
                break;
            }
        }
        accountPage();
    }

    /**
     * 无订单时无限等待订单，来回切换转账汇款和账号转账页，防止应用误操作超时退出
     */
    private void accountPage() {
        try {
            while (true) {
                UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/layout_trans_card"));
                UiObject accountTransfer;
                if (mBT_title.exists()) {
                    accountTransfer = mBT_title.getChild(new UiSelector().className("android.widget.TextView").index(1).text("账号转账"));
                    showMsg("点击账号转账");
                    if (accountTransfer != null && accountTransfer.exists()) {
                        showMsg("进入账号转账");
                        accountTransfer.click();
                        break;
                    }
                }
            }
            while (true) {
                sleep(ChatClient.overtime_3);
                addWorkTime(ChatClient.overtime_60);
                RUNING = list.size() > 0;
                showMsg("订单数为" + list.size());
                if (RUNING) {
                    orderBankName = Constants.getBank(list.get(0).getBankName(), "BOCB");
                    if (ConfirmOrder) {
                        getBalance(false);
                        showMsg("进入查账");
                        mDevice.pressBack();
                        sleep(ChatClient.overtime_3);
                        auditOrder();
                    } else {
                        showMsg("进入转账");
                        remittanceBusiness();
                    }
                } else {
                    if (PAUSE) {
                        showMsg("查询余额");
                        getBalance(true);
                        ChatClient.request();
                        backAccountPage1();
                    } else {
                        S_paused_C();
                        sleep(1000);
                    }
                }
            }
        } catch (Exception e) {
            setDevicesLog(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 查账业务
     */
    private void auditOrder() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowTime = System.currentTimeMillis();
            if ((nowTime - ChatClient.begintime) > ChatClient.overtime_10) {
                showMsg("点击转账记录超时");
                newAuditProcess();
                return;
            }
            UiObject transferRecord = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_trans_record").text("转账记录"));
            if (transferRecord.exists()) {
                showMsg("点击转账记录");
                transferRecord.click();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        BankOrder bankOrder = list.get(0);
        addWorkTime(ChatClient.overtime_60);
        UiObject transferRecordList = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/ll_right"));
        if (transferRecordList.exists()) {
            UiObject linearLayoutChild = transferRecordList.getChild(new UiSelector().resourceId("com.chinamworld.bocmbci:id/rl_content_above"));
            if (linearLayoutChild.exists()) {
                showMsg("点击最近一次转账记录");
                linearLayoutChild.click();
                sleep(ChatClient.overtime_5);
            }
        } else {
            showMsg("近期无交易明细");
            newAuditProcess();
            mDevice.pressBack();
            sleep(ChatClient.overtime_3);
            backAccountPage();
            return;
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_10) {
                newAuditProcess();
                mDevice.pressBack();
                sleep(ChatClient.overtime_2);
                mDevice.pressBack();
                sleep(ChatClient.overtime_5);
                backAccountPage();
                return;
            }
            UiObject transferTitle = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/titleValueTv").text("明细"));
            if (transferTitle.exists()) {
                showMsg("跳转到明细");
                break;
            }
        }
        String money = "", bankNo = "", name = "", businessStatus = "";
        UiObject mTV_amount, mTV_bankNo, mTV_name, mTV_businessStatus;
        // 获取交易详情的所有空间及内容
        UiObject bodyView = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/body_view"));
        UiObject bodyViewChild = bodyView.getChild(new UiSelector().className("android.widget.LinearLayout"));
        UiObject bodyViewChildChildName = bodyViewChild.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
        UiObject bodyViewChildChildChildName = bodyViewChildChildName.getChild(new UiSelector().resourceId("com.chinamworld.bocmbci:id/root_view"));
        UiObject bodyViewChildChildChildChildName = bodyViewChildChildChildName.getChild(new UiSelector().resourceId("com.chinamworld" +
                ".bocmbci:id/layout_body"));

        UiObject bodyViewChildChildAmount = bodyViewChild.getChild(new UiSelector().className("android.widget.LinearLayout").index(1));
        UiObject bodyViewChildChildChildAmount = bodyViewChildChildAmount.getChild(new UiSelector().resourceId("com.chinamworld" +
                ".bocmbci:id/root_view"));
        UiObject bodyViewChildChildChildChildAmount = bodyViewChildChildChildAmount.getChild(new UiSelector().resourceId("com.chinamworld" +
                ".bocmbci:id/layout_body"));

        mTV_amount = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_sum"));
        mTV_bankNo = bodyViewChildChildChildChildAmount.getChild(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_value").index(1));
        mTV_name = bodyViewChildChildChildChildName.getChild(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_value").index(1));
        mTV_businessStatus = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_status"));
        if (mTV_amount.exists()) {
            money = mTV_amount.getText().trim();
        }
        if (mTV_bankNo.exists()) {
            bankNo = mTV_bankNo.getText().trim();
            bankNo = bankNo.substring(bankNo.length() - 4);
        }
        if (mTV_name.exists()) {
            name = mTV_name.getText().trim();
        }
        if (mTV_businessStatus.exists()) {
            businessStatus = mTV_businessStatus.getText().trim();
        }
        showMsg("money=========" + money);
        if (!StringUtils.isEmpty(money)) {
            money = money.replaceAll("-", "");
            money = money.replaceAll(",", "");
        }

        if (Double.parseDouble(money) == Double.parseDouble(bankOrder.getMoney()) && bankNo.equals(list.get(0).getBankNo().substring(list.get(0)
                .getBankNo().length() - 4)) && name.equals(bankOrder.getUserName())) {
            failureToReport(businessStatus, Constants.getStr(businessStatus), 1);
        } else {
            newAuditProcess();
        }
        showMsg("返回记录列表页");
        mDevice.pressBack();
        sleep(ChatClient.overtime_3);
        showMsg("返回转账汇款页");
        mDevice.pressBack();
        sleep(ChatClient.overtime_3);
        backAccountPage();
    }

    /**
     * 查账时走金额变化判断  使用地方为：1、未找到和上一笔订单相同的金额和名称的订单 2、查账时出现异常超时 3、没有记录时
     */
    private void newAuditProcess() {
        showMsg("未查到相同订单");
        String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
        String oldMoney = FileHelper.readSDFile(sumMoneyFile);
        switch (Constants.changeInAmount(BANK_NAME, oldMoney, balance, list.get(0).getMoney())) {
            case "0":
                failureToReport("交易成功", 0, 1);
                break;
            case "1":
                failureToReport("交易待处理...", 1, 1);
                break;
            case "4":
                failureToReport("未查到条目", 4, 1);
                break;
        }
    }

    /**
     * 转账汇款业务
     */
    private void remittanceBusiness() throws UiObjectNotFoundException {
        BankOrder bankOrder = list.get(0);
        Constants.CODE = "";
        ChatClient.begintime = System.currentTimeMillis();
        getBalance(true);
        boolean next = determineBalance(bankOrder.getMoney());
        if (next) {
            sleep(ChatClient.overtime_1);
        } else {
            showMsg("余额不够，结束转账");
            sleep(ChatClient.overtime_3);
            return;
        }
        addWorkTime(ChatClient.overtime_60);
        EnterTheAmount();
        while (true) {
            UiObject mET_remittanceUserName = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/trans_remit_payeename").text
                    ("请输入"));
            if (mET_remittanceUserName.exists()) {
                showMsg("填入收款户名");
                mET_remittanceUserName.setText(bankOrder.getUserName());
                break;
            }
        }

        while (true) {
            UiObject mET_remittanceBankNo = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/clear_edit_context").text
                    ("请输入"));
            if (mET_remittanceBankNo.exists()) {
                showMsg("输入收款账户");
                mET_remittanceBankNo.click();
                sleep(1000);
                mDevice.click(75, 1930);
                sleep(1000);
                clickNumKey(bankOrder.getBankNo());
                sleep(2000);
                break;
            }
        }
        addWorkTime(ChatClient.overtime_20);
        while (true) {
            UiObject mTV_bankNameSelect = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/choice_data_name").text("收款银行"));
            if (mTV_bankNameSelect != null && mTV_bankNameSelect.exists()) {
                showMsg("选择收款银行");
                mTV_bankNameSelect.click();
                if (selectBank()) {
                    break;
                } else {
                    return;
                }
            }
        }

        while (true) {
            UiObject mBT = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/trans_remit_next").text("下一步"));
            if (mBT != null && mBT.exists()) {
                showMsg("确认转账");
                mBT.click();
                sleep(ChatClient.overtime_5);
                break;
            } else {
                //滑动
                mDevice.drag(180, 1616, 540, 1310, 10);
            }
        }

        UiObject dialogError = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_right"));
        if (dialogError.exists()) {
            showMsg("转账信息错误");
            dialogError.click();
            sleep(ChatClient.overtime_3);
            remittanceBusiness();
            return;
        }

        //判定转出账户是否正确
        while (true) {
            UiObject confirmTransferInformation = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_ok"));
            if (confirmTransferInformation != null && confirmTransferInformation.exists()) {
                showMsg("确认转账信息");
                String name = null, bankNo = null;
                UiObject mTV_name_title = mDevice.findObject(new UiSelector().text("收款人名称").resourceId("com.chinamworld.bocmbci:id/tv_name"));
                if (mTV_name_title.exists()) {
                    UiObject mTV_name = mTV_name_title.getFromParent(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_value").index(1));
                    if (mTV_name.exists()) {
                        name = mTV_name.getText();
                        if (StringUtils.isEmpty(name)) {
                            name = mTV_name.getContentDescription();
                        }
                        name = name.trim();
                    }
                }
                UiObject mTV_bankNo_title = mDevice.findObject(new UiSelector().text("收款账号").resourceId("com.chinamworld.bocmbci:id/tv_name"));
                if (mTV_bankNo_title.exists()) {
                    UiObject mTV_bankNo = mTV_bankNo_title.getFromParent(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_value").index(1));
                    if (mTV_bankNo.exists()) {
                        bankNo = mTV_bankNo.getText();
                        if (StringUtils.isEmpty(name)) {
                            bankNo = mTV_bankNo.getContentDescription();
                        }
                        bankNo = bankNo.replaceAll(" ", "");
                    }
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(bankNo)) {
                    showMsg("name---" + name + ",bankNo---" + bankNo);
                    if (name.equals(list.get(0).getUserName()) && bankNo.equals(list.get(0).getBankNo())) {
                        confirmTransferInformation.click();
                        sleep(ChatClient.overtime_3);
                        break;
                    } else {
                        ChatClient.timer(LogToFile.getMethodName(), "转账信息错误...");
                        return;
                    }
                }
            }
        }

        /*
         * 处理账单错误
         */
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_8) {
                showMsg("转账信息正确");
                break;
            }
            String errorMsg = errorMsg();
            if (!StringUtils.isEmpty(errorMsg)) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
                failureToReport(errorMsg, Constants.STATE_FAIL, 0);
                backAccountPage();
                return;
            }
        }
        /*
         * 处理短信与转账密码
         */
        smsFlag = 1;
        SMSOrPwd();
        /*
         * 结果页处理
         */
        orderFinish();
    }

    private void EnterTheAmount() throws UiObjectNotFoundException {
        while (true) {
            UiObject mET_setAmount = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/view_money"));
            if (mET_setAmount.exists()) {
                showMsg("点击汇款金额");
                mET_setAmount.click();
                sleep(2000);
                setClickMoney(list.get(0).getMoney());
                AmountOfContrast();
                break;
            }
        }
    }

    private void AmountOfContrast() throws UiObjectNotFoundException {
        showMsg("订单金额与输入金额对比");
        while (true) {
            UiObject mET_setAmount = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/view_money"));
            if (mET_setAmount.exists()) {
                String money = mET_setAmount.getText();
                if (Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(money.replaceAll(",", ""))) {
                    showMsg("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + mET_setAmount.getText() + "--->金额相等");
                } else {
                    int length = mET_setAmount.getText().length() + 1;
                    showMsg("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + mET_setAmount.getText() + "--->金额不相等");
                    sleep(1000);
                    mET_setAmount.click();
                    sleep(2000);
                    for (int i = 0; i < length; i++) {
                        mDevice.click(910, 1920);
                        sleep(500);
                    }
                    sleep(2000);
                    setClickMoney(list.get(0).getMoney());
                    sleep(1000);
                    AmountOfContrast();
                }
                break;
            }
        }
    }

    /**
     * 短信与转账密码处理
     */
    private void SMSOrPwd() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        if (user.getUseType().equals("1")) {
            showMsg("处理转账短信---真机");
            //10.1.0版本没有
            setPhoneSMS();
        } else {
            showMsg("处理转账短信---无SIM卡");
            setNotSIM_SMS();
        }
        sleep(ChatClient.overtime_3);
        errorSMSValidation();
    }

    /**
     * 处理无SIM卡手机短信逻辑
     */
    private void setNotSIM_SMS() {
        SMSCode smsCode = requestSMSCode(user.getUserName(), user.getBankId());
        if (StringUtils.isEmpty(smsCode.getSmscode())) {
            sleep(ChatClient.overtime_10);
            revalidate();
            setNotSIM_SMS();
        } else {
            clickNumKey1(smsCode.getSmscode());
        }
    }

    private void revalidate() {
        mDevice.click(611, 450);
        sleep(ChatClient.overtime_1);
        if (smsFlag < 3) {
            while (true) {
                UiObject mET_selectBank = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/security_retry").text("重新获取"));
                if (mET_selectBank.exists()) {
                    smsFlag++;
                    showMsg("重新获取");
                    try {
                        mET_selectBank.click();
                    } catch (UiObjectNotFoundException e) {
                        e.printStackTrace();
                    }
                    sleep(ChatClient.overtime_1);
                    mDevice.click(500, 1115);
                    break;
                }
            }
        } else {
            ChatClient.timer(LogToFile.getMethodName(), "短息获取超过三次");
        }
    }

    private void errorSMSValidation() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_20);
        /*
         * 转账错误处理
         */
        ChatClient.begintime = System.currentTimeMillis();
        showMsg("errorMsg()");
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_15) {
                showMsg("errorSMSValidation无错误提示");
                break;
            }
            String errorMsg = errorMsg1();
            if (!StringUtils.isEmpty(errorMsg)) {
                showMsg("StringUtils.isEmpty(errorMsg)：" + errorMsg);
                if (errorMsg.contains("错误")) {
                    showMsg("验证码输入错误次数：" + smsFlag);
                    sleep(ChatClient.overtime_2);
                    if (smsFlag < 3) {
                        while (true) {
                            UiObject mBT = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_ok").text("确认"));
                            if (mBT != null && mBT.exists()) {
                                showMsg("点击确认");
                                mBT.click();
                                sleep(ChatClient.overtime_3);
                                smsFlag++;
                                SMSOrPwd();
                                return;
                            }
                        }
                    } else {
                        ChatClient.timer(LogToFile.getMethodName(), "短息获取超过三次");
                        return;
                    }
                } else {
                    ChatClient.timer(LogToFile.getMethodName(), "错误信息不包括错误二字错误信息为：" + errorMsg);
                    return;
                }
            }
        }
    }

    /**
     * 监听短信点击输入验证码
     */
    private void setPhoneSMS() {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_45) {
                ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
                break;
            }
            if (TextUtils.isEmpty(Constants.CODE)) {
                sleep(3000);
            } else {
                showMsg("返回短信验证码为：" + Constants.CODE);
                break;
            }
        }
        sleep(3000);
        clickNumKey1(Constants.CODE);
        Constants.CODE = null;
    }

    /**
     * 转账结果页
     */
    private void orderFinish() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime = System.currentTimeMillis();
            if (nowTime - ChatClient.begintime > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), "转账结果页超时");
                return;
            }
            UiObject titleTv = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/titleValueTv"));
            if (titleTv.exists() && titleTv.getText().equals("操作结果")) {
                showMsg("进入操作结果果页");
                break;
            }
            sleep(1000);
        }

        while (true) {
            UiObject mTV_result = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_status").index(1));
            //需要确认状态都有啥
            if (mTV_result.exists()) {
                String text = mTV_result.getText();
                showMsg("转账结果---" + text);
                String errorStr = mTV_result.getText();
                int type = Constants.getStr(errorStr);
                if (type == 0) {
                    showMsg("balance---" + balance + "==list.get(0).getMoney()==" + list.get(0).getMoney());
                    DecimalFormat formater = new DecimalFormat("#0.##");
                    balance = formater.format(Double.parseDouble(balance) - Double.parseDouble(list.get(0).getMoney()));
                    failureToReport(errorStr, type, 0);
                    showMsg("本地保存余额");
                    String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                    FileHelper.saveMoneySDFile(false, balance, sumMoneyFile);
                    clickEnd();
                    break;
                } else {
                    failureToReport(errorStr, Constants.STATE_FAIL, 0);
                    clickEnd();
                    break;
                }
            }
        }
    }

    /**
     * 判定余额是否够本笔转账使用
     */
    private boolean determineBalance(String money) {
        balance = balance.replaceAll(",", "");
        if (Double.parseDouble(balance) >= Double.parseDouble(money)) {
            showMsg("余额够本次转账");
            return true;
        } else {
            failureToReport("账户余额不足", Constants.STATE_FAIL, 0);
            return false;
        }
    }

    /**
     * 查账订单状态上报
     *
     * @param info  状态
     * @param state 成功与否
     */
    private void failureToReport(String info, int state, int auditAndTransfer) {
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'" + BANK_NAME +
                "'," + "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':" + state + "," +
                "'type':1";
        showMsg("mobileD = " + mobileD);
        showMsg("json = " + json);
        String requestName;
        if (auditAndTransfer == 0) {
            requestName = ChatClient.M_SEND_TRADE_RESULT_P;
        } else {
            requestName = ChatClient.S_CONFIRM_TRADE_RESULT_C;
        }
        ChatClient.msg("<YZF>{'header':'" + requestName + "'," + json + "," + mobileD + "}</YZF>");
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
        sleep(ChatClient.overtime_2);
    }

    /**
     * 订单数据选择银行
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private boolean selectBank() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showMsg("无需选择银行");
                return true;
            }
            UiObject mTV_bankTitle1 = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_dialog_error_enter"));
            if (mTV_bankTitle1.exists()) {
                ChatClient.timer(LogToFile.getMethodName(), "您的网银会话已经超时，为了保证您的财产安全，已经自动退出网银服务");
                break;
            }
            UiObject mTV_bankTitle = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/titleValueTv").text("选择所属银行"));
            if (mTV_bankTitle.exists()) {
                showMsg("进入银行选择页面");
                break;
            }
        }

        while (true) {
            UiObject mET_selectBank = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/edit_content").text("请输入"));
            if (mET_selectBank.exists()) {
                showMsg("填入账单银行");
                mET_selectBank.setText(orderBankName);
                break;
            }
        }

        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                failureToReport("银行名称错误", 1, 0);
                sleep(ChatClient.overtime_3);
                mDevice.pressBack();
                sleep(ChatClient.overtime_3);
                mDevice.pressBack();
                sleep(ChatClient.overtime_2);
                while (true) {
                    UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/layout_trans_card"));
                    UiObject accountTransfer;
                    if (mBT_title.exists()) {
                        accountTransfer = mBT_title.getChild(new UiSelector().className("android.widget.TextView").index(1).text("账号转账"));
                        showMsg("点击账号转账");
                        if (accountTransfer != null && accountTransfer.exists()) {
                            showMsg("进入账号转账");
                            accountTransfer.click();
                            break;
                        }
                    }
                }
                return false;
            }
            UiObject mET_bankList = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_bank_name").text(orderBankName));
            if (mET_bankList.exists()) {
                showMsg("点击---" + orderBankName);
                mET_bankList.click();
                sleep(ChatClient.overtime_3);
                return true;
            }
        }
    }

    /**
     * 更新余额
     *
     * @param isSave 除查账外其他时间查账都要保存为保证余额的实时性 true:保存到本地 false：不保存
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void getBalance(boolean isSave) throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_2);
        addWorkTime(ChatClient.overtime_60);
        boolean boo = false;
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long beginTime1 = System.currentTimeMillis();
            if (beginTime1 - ChatClient.begintime > ChatClient.overtimeLogin) {
                ChatClient.timer(LogToFile.getMethodName(), "获取余额失败");
            }
            if (boo) {
                showMsg("获取余额失败");
                mDevice.pressBack();
                UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/layout_trans_card"));
                UiObject accountTransfer;
                if (mBT_title.exists()) {
                    accountTransfer = mBT_title.getChild(new UiSelector().className("android.widget.TextView").index(1).text("账号转账"));
                    showMsg("点击账号转账");
                    if (accountTransfer != null && accountTransfer.exists()) {
                        showMsg("进入账号转账");
                        accountTransfer.click();
                        sleep(ChatClient.overtime_5);
                    }
                }
            }
            showMsg("getBalance()");
            UiObject mLL = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/trans_accout_balance_currency").index(1));
            showMsg("getBalance()----mLL");
            if (mLL.exists()) {
                showMsg("getBalance()----mLL.exists()");
                balance = mLL.getText();
                balance = balance.replaceAll("人民币元", "");
                balance = balance.replaceAll(" ", "");
                balance = balance.replaceAll(",", "");
                if (!StringUtils.isEmpty(balance)) {
                    showMsg("余额---" + balance);
                    if (isSave) {
                        showMsg("本地保存余额");
                        String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                        FileHelper.saveMoneySDFile(false, balance, sumMoneyFile);
                    }
                    C_updateBalance_W(balance);
                    sleep(ChatClient.overtime_1);
                    break;
                }
            } else {
                boo = true;
            }
        }
    }

    /**
     * 输入金额
     *
     * @param pad_ 金额
     */
    private void setClickMoney(String pad_) {
        showMsg("点击汇款金额=======" + pad_);
        char[] abc = "123456789.0".toCharArray();//char数组
        char[] pwd = pad_.toCharArray();//char数组
        for (char c : pwd) {
            Log.d(TAG, "======c=======" + c);
            for (int i = 0; i < abc.length; i++) {
                if (abc[i] == c) {
                    mDevice.click(xy_123_2016[i][0], xy_123_2016[i][1]);
                    sleep(1000);
                    break;
                }
            }
        }
        // 收起键盘
        mDevice.click(611, 450);
    }

    /**
     * 输入收款账号及短信验证码
     *
     * @param bankNo 收款账号及短信验证码
     */
    private void clickNumKey(String bankNo) {
        char[] array = bankNo.toCharArray();
        for (char c : array) {
            int i = Integer.parseInt(String.valueOf(c));
            mDevice.click(xy_bank_no_2016[i][0], xy_bank_no_2016[i][1]);
//            showMsg("点击---" + i);
            sleep(1000);
        }
        mDevice.click(990, 1345);
        mDevice.click(990, 1345);

        showMsg("卡号输入完成，收回键盘");
    }

    /**
     * 输入短信验证码
     *
     * @param bankNo 短信验证码
     */
    private void clickNumKey1(String bankNo) {
        char[] array = bankNo.toCharArray();
        for (char c : array) {
            int i = Integer.parseInt(String.valueOf(c));
            mDevice.click(xy_sms_2016[i][0], xy_sms_2016[i][1]);
//            showMsg("点击---" + i);
            sleep(1000);
        }
        showMsg("卡号输入完成，收回键盘");
    }

    /**
     * 点击完成返回账户总览
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void clickEnd() throws UiObjectNotFoundException {
        mDevice.drag(50, 800, 50, 300, 20);
        sleep(ChatClient.overtime_2);
        while (true) {
            UiObject okBtn = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/choice_data_name").text("继续转账"));
            if (okBtn.exists()) {
                showMsg("点击《继续转账》按钮");
                okBtn.click();
                sleep(ChatClient.overtime_5);
                break;
            }
        }
    }

    private String errorMsg() throws UiObjectNotFoundException {
        UiObject errorMsgTitle = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_notice"));
        UiObject errorMsgBtn;
        String errorResult;
        if (errorMsgTitle.exists()) {
            errorResult = errorMsgTitle.getText();
            showMsg("errorMsg  = " + errorResult);
            errorMsgBtn = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_right"));
            if (errorMsgBtn.exists()) {
                showMsg("点击提示弹窗《确定》");
                errorMsgBtn.click();
                return errorResult;
            }
        }
        return "";
    }

    private String errorMsg1() throws UiObjectNotFoundException {
        UiObject errorMsgTitle = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_dialog_error_content"));
        UiObject errorMsgBtn;
        String errorResult;
        if (errorMsgTitle.exists()) {
            errorResult = errorMsgTitle.getText();
            showMsg("errorMsg  = " + errorResult);
            errorMsgBtn = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/btn_dialog_error_enter"));
            if (errorMsgBtn.exists()) {
                showMsg("点击提示弹窗《确定》");
                errorMsgBtn.click();
                return errorResult;
            }
        }
        return "";
    }

    /**
     * 等待订单
     */
    private void backAccountPage1() throws UiObjectNotFoundException {
        if (ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            orderBankName = Constants.getBank(list.get(0).getBankName(), BANK_NAME);
            // 转账
            showMsg("进入转账");
            remittanceBusiness();
            return;
        }
        sleep(ChatClient.overtime_2);
        showMsg("backAccountPage1()");
        UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/choice_data_name").text("付款账户"));
        if (mBT_title.exists()) {
            showMsg("已到付款账户");
            mBT_title.click();
        }
        sleep(ChatClient.overtime_5);
        UiObject tv_name = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_name"));
        if (tv_name.exists()) {
            showMsg("点击长城电子借记卡 ");
            tv_name.click();
        } else {
            mDevice.pressBack();
        }
    }

    /**
     * 返回转账汇款页
     */
    private void backAccountPage() throws UiObjectNotFoundException {
        showMsg("backAccountPage()");
        while (true) {
            showMsg("backAccountPage()-----while (true)");
            UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/titleValueTv").text("转账汇款"));
            if (mBT_title.exists()) {
                showMsg("backAccountPage()-----while (true)-----if");
                showMsg("已返回转账汇款");
                sleep(ChatClient.overtime_3);
                break;
            } else {
                showMsg("backAccountPage()-----while (true)-----else");
                mDevice.pressBack();
                sleep(ChatClient.overtime_3);
                UiObject mTV_myAccount = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/tv_item").text("转账"));
                if (mTV_myAccount.exists()) {
                    showMsg("点击---转账");
                    mTV_myAccount.click();
                    break;
                }
            }
        }
        while (true) {
            UiObject mBT_title = mDevice.findObject(new UiSelector().resourceId("com.chinamworld.bocmbci:id/layout_trans_card"));
            UiObject accountTransfer;
            if (mBT_title.exists()) {
                accountTransfer = mBT_title.getChild(new UiSelector().className("android.widget.TextView").index(1).text("账号转账"));
                showMsg("点击账号转账");
                if (accountTransfer != null && accountTransfer.exists()) {
                    showMsg("进入账号转账");
                    accountTransfer.click();
                    break;
                }
            }
        }
    }

    public static void showMsg(String msg) {
        LogToFile.showLog(BANK_NAME, msg);
    }
}
